//
//  InvestmentConfirmVC.m
//  HengYouCai
//
//  Created by ycgwl on 2017/4/28.
//  Copyright © 2017年 lwj. All rights reserved.
//
#import "InvestmentConfirmVC.h"
// 充值
#import "RechargeViewController.h"
#import "PswInputView.h"
#import "ChangePasswordVC.h"
#import "RedPackModel.h"
#import "FinishInviteVC.h"
#import "BonusesView.h"
#import "QuanModel.h"
#import "BannerWebViewVC.h"
#import "RiskAlertView.h"
#import "GetBackPasswordVC.h"
#import "RedPackModel.h"
#import "HengYouCai-Swift.h"
#import <ReactiveObjC/RACReturnSignal.h>
@interface InvestmentConfirmVC ()<UIScrollViewDelegate,UITableViewDelegate,UITextFieldDelegate>
{
    BOOL _isAgree;
    NSString *_productID;
    // 红包 加息券的id 和 数值
    NSString *_quanID;
    NSString *_redID;
    // 加息xxx
    NSString *_quan;
    // 当前所选红包的额度
    NSString *_currentRedMoney;
    // 有几个可用加息券
    NSString *_quanUse;
    NSString *_redMoneyUse;
    // 当前选中的红包 加息券 用于 记录 列表的 选中状态
    NSInteger _currentQuanIndex;
    NSInteger _currentRedIndex;
    // 是否有可用红包加息券
    BOOL _isHaveRed;
    BOOL _isHaveCoupon;
    // 当输入金额发生改变是 清空选中的红包 加息券 并且重新 请求数据 刷新tableview
    NSString *_currenMoney;
    // 可用返现红包的总额
    float _allRedMoney;
    
}
//风险提示按钮
@property (weak, nonatomic) IBOutlet UIButton *riskButton;
//子壹财富协议
@property (weak, nonatomic) IBOutlet UIButton *protocolButton;

@property (weak, nonatomic) IBOutlet UITableView *myTableView;
/**
 加息券
 */
@property (weak, nonatomic) IBOutlet UILabel *jiaXiQuanLab;

/**
 立即投资按钮
 */
@property (weak, nonatomic) IBOutlet UIButton *investBtn;

/**
 预估总收益
 */
@property (weak, nonatomic) IBOutlet UILabel *earningMonry;

/**
 可用金额
 */
@property (weak, nonatomic) IBOutlet UILabel *usingMoney;

/**
 投资输入框
 */
@property (weak, nonatomic) IBOutlet UITextField *moneyTF;

/**
 控制新手标预估总收益上移
 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topToFooterView;

/**
 返现红包view 用于新手标的时候隐藏
 */
@property (weak, nonatomic) IBOutlet UIView *cashBackView;
/**
 加息券view 用于新手标的时候隐藏
 */
@property (weak, nonatomic) IBOutlet UIView *jiaXiquan;
/**
 基本收益view 用于新手标的时候隐藏
 */
@property (weak, nonatomic) IBOutlet UIView *baseProfitView;

/**
 返现红包
 */
@property (weak, nonatomic) IBOutlet UILabel *cashRed;

/**
 基本收益
 */
@property (weak, nonatomic) IBOutlet UILabel *baseProfit;

/**
 加息券列表
 */
@property (nonatomic, retain)NSMutableArray *couponList;
/**
 红包列表
 */
@property (nonatomic, retain)NSMutableArray *redList;

/**
 cell的标题数组 用于判断有几个cell
 */
@property (nonatomic, retain) NSArray *titleArr;

/**
 投资时间 用于投资完成界面展示
 */
@property (nonatomic, copy)NSString  *inviteTime;

/**
 当前数据源
 */
@property (nonatomic, retain)ProjectModel *currentModel;

/**
 当前标的类型（新手标 和 普通标）
 */
@property (nonatomic, copy)NSString  *currentType;
//历史年化收益
@property (weak, nonatomic) IBOutlet UILabel *leftStatusLabel;
//投资期限
@property (weak, nonatomic) IBOutlet UILabel *middleStatusLabel;
//剩余可投
@property (weak, nonatomic) IBOutlet UILabel *rightStatusLabel;
//账户余额
@property (weak, nonatomic) IBOutlet UILabel *accountBanlanceLabel;
//余额充值
@property (weak, nonatomic) IBOutlet UIButton *rechargeButton;
//投资金额
@property (weak, nonatomic) IBOutlet UILabel *amountLabel;
//剩余t全投
@property (weak, nonatomic) IBOutlet UIButton *amountButtonLabel;
//红包
@property (weak, nonatomic) IBOutlet UILabel *redPacketLabel;
//加息券
@property (weak, nonatomic) IBOutlet UILabel *couponLabel;
//基本收益
@property (weak, nonatomic) IBOutlet UILabel *baseProfitLabel;
@property (weak, nonatomic) IBOutlet UILabel *totalProfitLabel;

@property(nonatomic,copy)NSString *investmentAgreementName;//子壹财富投资协议
@property(nonatomic,copy)NSString *riskReminderName;//子壹财富投资协议

@end

@implementation InvestmentConfirmVC
- (void)dealloc
{

    NSLog(@"InvestmentConfirmVC=======");
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
    
    if (_productID) {
        [HYCNetService productsStateWithDict:@{@"id":_productID} onSuccess:^(NSDictionary *dictResult) {
            
            self.currentModel = [ProjectModel mj_objectWithKeyValues:dictResult[@"products"]];
            self.navigationItem.title = self.currentModel.title;
            // 用于下面判断
            self.currentModel.surplusAmount2 = dictResult[@"surplusAmount2"];
            // 页面赋值
            [self refreshHeadViewWithModel:dictResult];
        } andFailed:^(NSInteger code, NSString *errorMsg) {
            
        }];
    }
    
}
- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)hideKeyBoard
{
    
        WLGetWeakSelf(wekSelf, self);

        if ((_quanID.length>0)) {
            // 金额改变 清除已经选择的券
            _quanID = @"";
            _quan = @"";
            _redID = @"";
            _redMoneyUse = @"";
            _currentRedIndex = 10000;
            _currentQuanIndex = 10000;
            // 计算预估收益
            [self yugushouyiWithMoney:[NSString stringWithFormat:@"%ld",_moneyTF.text.integerValue ?: 0 ]];
        }
        if (_currentModel) {
            // 获取可用加息券
            [HYCNetService productsBoundsWithDict:@{@"id":_currentModel.ID,@"amount":[NSString stringWithFormat:@"%ld",_moneyTF.text.integerValue ?: 0]} onSuccess:^(NSDictionary *dictResult) {
                
                //  加息券 数组
                wekSelf.redList = [RedPackModel mj_objectArrayWithKeyValuesArray:dictResult[@"redList"]];
                wekSelf.couponList = [RedPackModel mj_objectArrayWithKeyValuesArray:dictResult[@"couponList"]];
                // 可用 加息券的 数量
                NSString *availableCouponCount = dictResult[@"availableCouponCount"];
                NSString *availableRedCount = dictResult[@"availableRedCount"];

                // 是否有 可用 加息券
                _isHaveRed = availableRedCount.integerValue > 0;
                _redMoneyUse = dictResult[@"redPacketTips"];
                //_isHaveRed ? [NSString stringWithFormat:@"有%@个可用红包",availableRedCount] : @"无红包可用";
                _cashRed.text = _redMoneyUse;
                _isHaveCoupon = availableCouponCount.integerValue > 0;
                _quanUse = dictResult[@"couponsTips"];
                //_isHaveCoupon ? [NSString stringWithFormat:@"有%@个可用加息券",availableCouponCount] : @"无加息券可用";
                // 刷新tableView
                [wekSelf yugushouyiWithMoney:[NSString stringWithFormat:@"%ld",_moneyTF.text.integerValue ?: 0 ]];
                
            } andFailed:^(NSInteger code, NSString *errorMsg) {
                
            }];
        }
        
    
//    }
}
- (void)setUI
{
    UIView *headView = [[[self.myTableView.tableHeaderView viewWithTag:11] viewWithTag:102] viewWithTag:1001];

    headView.layer.shadowColor = UIColor.blackColor.CGColor;
    headView.layer.shadowOpacity = 0.3;
    headView.layer.shadowOffset = CGSizeMake(0, 0);

//    // 新手标 就隐藏基本收益 返现红包
//    if ([_currentType isEqualToString:@"-1"]) {
//        _topToFooterView.constant = 7;
//        _baseProfitView.hidden = YES;
//        _cashBackView.hidden = YES;
//        _jiaXiquan.hidden = YES;
//    }
    _currentRedIndex = 10000;
    _currentQuanIndex = 10000;
    // 起投金额 剩余可投
    NSInteger investBegin = _currentModel.investBegin.integerValue;
    NSInteger surplusAmount = _currentModel.surplusAmount.integerValue;
    [self.moneyTF.rac_textSignal subscribeNext:^(NSString * _Nullable x) {
        
        NSInteger money = [x integerValue];
        // 金额 大于起投金额 可点击 &&x.length>0防止第一次点击收入框可点击
        if (money >= _currentModel.investBegin.integerValue&&x.length>0) {
            _investBtn.backgroundColor = Normal_RedColor;
            _investBtn.enabled = YES;
            
        }else{
            
            _investBtn.backgroundColor = Normal_UnselecBtnColor;
            _investBtn.enabled = NO;
            
        }
        
        if (investBegin > surplusAmount) {
            // 当起投金额 大于 剩余可投的时候 输入金额== 剩余可投 btn可点击
            if (money == surplusAmount) {
                _investBtn.backgroundColor = Normal_RedColor;
                _investBtn.enabled = YES;
            }
        }
        
    }];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 默认同意协议
    _isAgree = YES;
    _moneyTF.delegate = self;
    [self setUI];
}

/**
 剩余全投
 */
- (IBAction)allIn:(UIButton *)sender {
    
    // 起投金额
    NSInteger investBegin = _currentModel.investBegin.integerValue;
    // 剩余可投
    NSInteger surplusAmount = _currentModel.surplusAmount.integerValue;
    // 钱包余额
    NSInteger walletBalance  = _usingMoney.text.integerValue;
    
    if ([_currentModel.type isEqualToString:@"-1"]) {//新手标
        //min 三个值之间取最小值(新手标剩余可投 新手标投资限额 剩余可投)
        NSArray *array = [NSArray arrayWithObjects:_currentModel.surplusAmount?:@"",_currentModel.surplusAmount2?:@"" ,_currentModel.investEnd?:@"", nil];
        NSInteger min =[[array valueForKeyPath:@"@min.floatValue"] integerValue];
        _moneyTF.text = [NSString stringWithFormat:@"%zd",min];
        
        if (investBegin <= walletBalance && walletBalance <= min) {
            _moneyTF.text = [NSString stringWithFormat:@"%zd",walletBalance/100*100];
        }else if (walletBalance <= investBegin && investBegin <= min){
            _moneyTF.text = [NSString stringWithFormat:@"%zd",investBegin];
            
        }else{
            _moneyTF.text = [NSString stringWithFormat:@"%zd",min];
            
        }
        
        if (_moneyTF.text.integerValue > 0) {
            _investBtn.enabled = YES;
            _investBtn.backgroundColor = Normal_RedColor;
        }else{
            _investBtn.enabled = NO;
            _investBtn.backgroundColor = Normal_UnselecBtnColor;
        }
        
    }else{//正常标
        
        if (investBegin <= walletBalance && walletBalance <= surplusAmount) {
            _moneyTF.text = [NSString stringWithFormat:@"%ld",walletBalance/100*100];
        }else if (walletBalance <= investBegin && investBegin <= surplusAmount){
            _moneyTF.text = [NSString stringWithFormat:@"%ld",investBegin];
            
        }else{
            _moneyTF.text = [NSString stringWithFormat:@"%ld",surplusAmount];
            
        }
        
        if (_moneyTF.text.integerValue > 0) {
            _investBtn.enabled = YES;
            _investBtn.backgroundColor = Normal_RedColor;
        }else{
            _investBtn.enabled = NO;
            _investBtn.backgroundColor = Normal_UnselecBtnColor;
        }
    }
    
    [self hideKeyBoard];
    
}
/**
 立即充值
 */
- (IBAction)depositAtOnce:(UIButton *)sender {
    
    
    RechargeViewController *VC = [[UIStoryboard storyboardWithName:@"Profile" bundle:nil] instantiateViewControllerWithIdentifier:@"RechargeViewControllerID"];
    [self.navigationController pushViewController:VC animated:YES withHideBottomBarWhenPush:YES pop:YES];
}


- (void)refreshHeadViewWithModel:(NSDictionary *)dic{
    [self.myTableView reloadData];
    
    self.leftStatusLabel.text = dic[@"profitLabel"];
    self.middleStatusLabel.text = dic[@"plstimeLimitLabel"];
    if ([self.currentModel.type isEqualToString:@"0"]) {
        self.rightStatusLabel.text  = dic[@"surplusAmountLabel"];
    }else{
        self.rightStatusLabel.text  = dic[@"investEndLabel"];
    }
    self.accountBanlanceLabel.text = dic[@"balanceLabel"];
//    self.rechargeButton.titleLabel.text = dic[@"rechargeButtonLabel"];
    [self.rechargeButton setTitle:dic[@"rechargeButtonLabel"] forState:UIControlStateNormal];
    self.amountLabel.text = dic[@"amountLabel"];
    self.moneyTF.placeholder = dic[@"amountTips"];
//    self.amountButtonLabel.titleLabel.text = dic[@"amountButtonLabel"];
    [self.amountButtonLabel setTitle:dic[@"amountButtonLabel"] forState:UIControlStateNormal];
    
    self.redPacketLabel.text = dic[@"redPacketLabel"];
    self.couponLabel.text = dic[@"couponsLabel"];
    
    self.baseProfitLabel.text = dic[@"basicProfitLabel"];
    
    self.totalProfitLabel.text = dic[@"totalProfitLabel"];
    
//    self.investBtn.titleLabel.text  = dic[@"buttonLabel"];
    [self.investBtn setTitle:dic[@"buttonLabel"] forState:UIControlStateNormal];
    
    if (![dic[@"redPacketStatus"] boolValue]) { //红包隐藏
            _cashBackView.hidden = YES;
    }
    if (![dic[@"couponsStatus"] boolValue]) { //加息券
        _jiaXiquan.hidden = YES;
    }
    if (![dic[@"redPacketStatus"] boolValue] && ![dic[@"couponsStatus"] boolValue]) { //只显示预估总收益
        _topToFooterView.constant = 7;
        _baseProfitView.hidden = YES;
        _cashBackView.hidden = YES;
        _jiaXiquan.hidden = YES;
    }
    [self.protocolButton setTitle:[NSString stringWithFormat:@"《%@》",dic[@"investmentAgreementName"]] forState:UIControlStateNormal];
    [self.riskButton setTitle:[NSString stringWithFormat:@"《%@》",dic[@"riskReminderName"]] forState:UIControlStateNormal];
    
    self.investmentAgreementName = dic[@"investmentAgreementName"];
    self.riskReminderName = dic[@"riskReminderName"];
    
    
    // 投资金额的placeHolder
//    _moneyTF.placeholder = [NSString stringWithFormat:@"%@起投，每100元累加",dic[@"products"][@"investBegin"]];
    
    ProjectModel *detailmodel = [ProjectModel mj_objectWithKeyValues:dic[@"products"]];
    UIView *headView = [self.myTableView.tableHeaderView viewWithTag:100];
    
    UILabel *titleLab = [headView viewWithTag:30000];
    UILabel *minProfitLab = [headView viewWithTag:1003];
    UILabel *plstimeLimitValueLab = [headView viewWithTag:1004];
    UILabel *surplusAmountLab = [headView viewWithTag:1008];
    
    titleLab.text = detailmodel.title;
    _usingMoney.text = [NSString stringWithFormat:@"%@元",dic[@"userAccount"][@"availableMoney"]];
    
    CGFloat minProfit = [detailmodel.minProfit floatValue]*100;
    minProfitLab.text = [NSString stringWithFormat:@"%.2f%%",minProfit];
    NSString *limitType = [detailmodel.plstimeLimitType isEqualToString:@"0"]?@"天":@"个月";
    plstimeLimitValueLab.text = [NSString stringWithFormat:@"%@%@",detailmodel.plstimeLimitValue,limitType];
    self.inviteTime = plstimeLimitValueLab.text;
    
//    UILabel *endLab = [headView viewWithTag:20000];
    if ([detailmodel.type isEqualToString:@"-1"]) {
        
//        endLab.text = @"投资限额";
        surplusAmountLab.text = [NSString stringWithMoneyNoPointAndYuan:detailmodel.investEnd] ;
        
    }else{
        
//        endLab.text = @"剩余可投";
        surplusAmountLab.text = [NSString stringWithMoneyNoPointAndYuan:detailmodel.surplusAmount];
        
    }
    
}
- (void)yugushouyiWithMoney:(NSString *)money{
    if (_productID) {
        // 预估总收益
        [HYCNetService productsCalculationProfitWithDict:@{@"id":_productID,@"amount":money,@"couponId":_quanID?:@""} onSuccess:^(NSDictionary * dictResult) {
            
            CGFloat allProfit = [dictResult[@"profit"] floatValue];
            CGFloat baseProfit = [dictResult[@"profit1"] floatValue];
            
            // 加息券收益
            _quan = [NSString stringWithFormat:@"%@元",dictResult[@"profit2"]];
            // 预估总收益
            _earningMonry.text = [NSString stringWithFormat:@"%.2f元",allProfit];
            // 基本收益
            _baseProfit.text = [NSString stringWithFormat:@"%.2f元",baseProfit];
            
            if (_quanID.length > 0) {
                
                _jiaXiQuanLab.attributedText = [NSString stringWithStrArray:@[@"加息券收益",_quan] colorArray:@[Normal_666Color,Normal_RedColor]];
            }else{
                _jiaXiQuanLab.attributedText =[ [NSMutableAttributedString alloc] initWithString:_quanUse];
            }
//            [self.myTableView reloadData];
            
        } andFailed:^(NSInteger code, NSString *errorMsg) {
            
        }];
        
    }
    
}
- (void)canInvest{
    
    WLGetWeakSelf(weakSelf, self);
    
    
    /**
     显示密码框
     */
    NSInteger finalMoney = [_moneyTF.text integerValue];
    
    [PswInputView initWithFrame:CGRectMake(0, 0, f_Device_w, f_Device_h) money:[NSString stringWithFormat:@"￥%zd",finalMoney] psdBlock:^(NSString *str, PswInputView *pswView) {
        
        /**
         获取到密码
         */
        
        NSDictionary *dic = @{@"redId":_redID?:@"",
                              @"couponId":_quanID?:@"",
                              @"paypassword":str,
                              @"productsId":_productID,
                              @"amount":_moneyTF.text,
                              @"actualAmount":[NSString stringWithFormat:@"%ld",finalMoney - _currentRedMoney.integerValue]};
        
        
        [HYCNetService productsPaymentWithDict:dic onSuccess:^(NSDictionary *dictResult) {
            // 要放在前面
            [weakSelf.view hideHUDLoading:0];
            [pswView removeFromSuperview];
            FinishInviteVC *finish = [[UIStoryboard storyboardWithName:@"Profile" bundle:nil] instantiateViewControllerWithIdentifier:@"FinishInviteVCID"];
            
            finish.paymentSuccessTitle = dictResult[@"paymentSuccessTitle"];
            finish.paymentSuccessTips = dictResult[@"paymentSuccessTips"];
            finish.paymentSuccessAmountLabel = dictResult[@"paymentSuccessAmountLabel"];
            finish.paymentSuccessPlstimeLimitLabel = dictResult[@"paymentSuccessPlstimeLimitLabel"];
            finish.paymentSuccessProfitLabel = dictResult[@"paymentSuccessProfitLabel"];
            finish.paymentSuccessRewardLabel = dictResult[@"paymentSuccessRewardLabel"];
            finish.paymentSuccessrRwardTips = dictResult[@"paymentSuccessrRwardTips"];
            
            
            finish.modelArr = [TouziZengSongModel mj_objectArrayWithKeyValuesArray:dictResult[@"userBonusesList"]];
            
            finish.totalArr = @{@"inviteMoney":_moneyTF.text,
                                @"inviteTime":self.inviteTime,
                                @"yuGuShouYi":[NSString stringWithFormat:@"%@元",dictResult[@"profit"]]};
            
            [weakSelf presentViewController:finish animated:YES completion:^{
                
                // 充值成功 清空数据
                _quan = @"";
                _quanID = @"";
                _quanUse = @"";
                _moneyTF.text = @"";
                _investBtn.enabled = NO;
                _investBtn.backgroundColor = Normal_UnselecBtnColor;
                _earningMonry.text = @"";
                
                [weakSelf.navigationController popToRootViewControllerAnimated:YES];
                weakSelf.tabBarController.selectedIndex = 1;
            }];
            
        } andFailed:^(NSInteger code, NSString *errorMsg) {
            [weakSelf.view hideHUDLoading:0];
            if (code == 100) {
                pswView.errorMessageLab.text = errorMsg;
                //                    pswView.psdField.text = @"";
                UIImageView *img1 = [pswView viewWithTag:10001];
                UIImageView *img2 = [pswView viewWithTag:10002];
                UIImageView *img3 = [pswView viewWithTag:10003];
                UIImageView *img4 = [pswView viewWithTag:10004];
                UIImageView *img5 = [pswView viewWithTag:10005];
                UIImageView *img6 = [pswView viewWithTag:10006];
                
                img1.hidden = YES;
                img2.hidden = YES;
                img3.hidden = YES;
                img4.hidden = YES;
                img5.hidden = YES;
                img6.hidden = YES;
                
                CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
                animation.values = @[
                                     [NSValue valueWithCGPoint:pswView.errorMessageLab.layer.position],
                                     [NSValue valueWithCGPoint:CGPointMake(pswView.errorMessageLab.layer.position.x-20, pswView.errorMessageLab.layer.position.y)],
                                     [NSValue valueWithCGPoint:CGPointMake(pswView.errorMessageLab.layer.position.x+20, pswView.errorMessageLab.layer.position.y)],
                                     [NSValue valueWithCGPoint:pswView.errorMessageLab.layer.position]
                                     ];
                animation.keyTimes = @[
                                       @(0),@(0.3),@(0.7),@(1)
                                       ];
                animation.autoreverses = NO;
                animation.duration = 0.5;
                [pswView.errorMessageLab.layer addAnimation:animation forKey:@"anmi"];
            }else if (code == 200){
                
                [pswView removeFromSuperview];
                [[JCWCommonAlertView alloc] initWithTitle:@"温馨提示" message:errorMsg btnTitle:@"立即充值" sureClick:^{
                    
                    RechargeViewController *VC = [[UIStoryboard storyboardWithName:@"Profile" bundle:nil] instantiateViewControllerWithIdentifier:@"RechargeViewControllerID"];
                    [weakSelf.navigationController pushViewController:VC animated:YES withHideBottomBarWhenPush:YES pop:YES];
                }];
                
            }else if (code == 1){
                [weakSelf.view showHUDFailTips:errorMsg hideDelay:2];
                [pswView removeFromSuperview];
            }else{
                [pswView removeFromSuperview];
            }
            
        }];
        
        
    } forgetPsd:^{
        //
        /**
         忘记密码
         */
        GetBackPasswordVC *change = [[UIStoryboard storyboardWithName:@"Profile" bundle:nil] instantiateViewControllerWithIdentifier:@"GetBackPasswordVCID"];
        [weakSelf.navigationController pushViewController:change animated:YES withHideBottomBarWhenPush:YES pop:YES];
    }];
    
}
/**
 选择红包
 */
- (IBAction)choseRedPack:(UIButton *)sender {
    
    if (_redList.count<1) {
        return;
    }
    [BonusesView initWithFrame:CGRectMake(0, 0, f_Device_w, f_Device_h) currentType:@"-100" investBeginMoney:_moneyTF.text serviceConditionsLimitType:_currentModel.plstimeLimitType serviceConditionsLimitValue:_currentModel.plstimeLimitValue currentIndex:_currentRedIndex title:@"红包" dataArray:_redList  bonuseBlock:^(NSString *bonuseId) {
        NSInteger redID = [bonuseId integerValue];
        _currentRedIndex = redID;
        if (redID == 10000) {
            _redID = @"";
            _cashRed.text = _redMoneyUse;
            _currentRedMoney = @"0";

        }else{
            RedPackModel *model = _redList[redID];
            _redID = model.redOrCouponId;
            NSString *str = model.bonuses;
            _currentRedMoney = str;
            _cashRed.attributedText = [NSString stringWithStrArray:@[@"红包抵扣",_currentRedMoney,@"元"] colorArray:@[Normal_666Color,Normal_RedColor,Normal_RedColor]];
        }
        
    }];
}
// 选择加息券
- (IBAction)choseJiaXiQuan:(id)sender {
    
    if (_couponList.count<1) {
        return;
    }
    [BonusesView initWithFrame:CGRectMake(0, 0, f_Device_w, f_Device_h) currentType:@"-200" investBeginMoney:_moneyTF.text serviceConditionsLimitType:_currentModel.plstimeLimitType serviceConditionsLimitValue:_currentModel.plstimeLimitValue currentIndex:_currentQuanIndex title:@"加息券" dataArray:_couponList  bonuseBlock:^(NSString *bonuseId) {
        NSInteger quanID = [bonuseId integerValue];
        _currentQuanIndex = quanID;
        if (quanID == 10000) {
            _quanID = @"";
            [self yugushouyiWithMoney:[NSString stringWithFormat:@"%ld",_moneyTF.text.integerValue ?: 0 ]];
        }else{
            RedPackModel *model = _couponList[quanID];
            _quanID = model.redOrCouponId;
            NSString *str = model.bonuses;
            _quan = str;
            // 有加息券 的 话 重新计算预估收益
            [self yugushouyiWithMoney:[NSString stringWithFormat:@"%ld",_moneyTF.text.integerValue ?: 0 ]];
        }
        
    }];
}


/**
 确认投资按钮
 */
- (IBAction)investmentConfirm:(UIButton *)sender {
    
    if (!_isAgree) {
        [self.view showHUDWarnTips:[NSString stringWithFormat:@"请阅读并同意《%@》和《%@》",self.investmentAgreementName,self.riskReminderName]
                         hideDelay:1.5];
        return;
    }
    NSInteger moneymoney = [_moneyTF.text integerValue];
    
    if (moneymoney%100!=0) {
        [self.view showHUDWarnTips:@"请输入100的整数倍" hideDelay:1];
        return;
    }
    
    [self.view endEditing:YES];
    [self.view showHUDLoadingTips:@""];
    WLGetWeakSelf(weakSelf, self);
    [HYCNetService getFindUserMaxInvestWithDict:@{@"invest":_moneyTF.text} OnSuccess:^(NSDictionary *dictResult) {
        
        [weakSelf.view hideHUDLoading:0];
        if (dictResult) {
            
            
            if ([dictResult[@"current_level"] isEqualToString:@"-1"]) {
                
                NSString *current_level_description = dictResult[@"current_level_description"];
                NSArray *descArr = [current_level_description componentsSeparatedByString:@"“"];
                [RiskAlertView initWithFrame:self.view.frame title:@"温馨提示" type:descArr[0] desc:[NSString stringWithFormat:@"”%@",descArr[1]] otherDesc:dictResult[@"max_level_description"] firstBtn:@"立即测评" secondBtn:@"一键默认" firsBlock:^{
                    
                    [self.navigationController pushViewController:[RiskAppraiseViewC new] animated:YES withHideBottomBarWhenPush:YES pop:YES];
                } seconBlock:^{
                    [HYCNetService getUpdateUserDefaultLevelOnSuccess:^(NSDictionary *dictResult) {
                        [weakSelf canInvest];
                        
                    } andFailed:^(NSInteger code, NSString *errorMsg) {
                    }];
                }];
                
            }else{
                
                [RiskAlertView initWithFrame:self.view.frame title:@"温馨提示" type:dictResult[@"current_level_description"] desc:@"" otherDesc:dictResult[@"max_level_description"] firstBtn:@"重新测评" secondBtn:@"一键默认" firsBlock:^{
                    
                    [self.navigationController pushViewController:[RiskAppraiseViewC new] animated:YES withHideBottomBarWhenPush:YES pop:YES];
                } seconBlock:^{
                    [HYCNetService getUpdateUserDefaultLevelOnSuccess:^(NSDictionary *dictResult) {
                        [weakSelf canInvest];
                        
                    } andFailed:^(NSInteger code, NSString *errorMsg) {
                    }];
                }];
            }
            
        }else{
            [weakSelf canInvest];
        }
        
        
    } andFailed:^(NSInteger code, NSString *errorMsg) {
        
        [weakSelf.view showHUDFailTips:errorMsg hideDelay:1];
        
    }];
    
    
}
/**
 同意协议
 
 */
- (IBAction)agreeBtnClick:(UIButton *)sender {
    
    _isAgree = !_isAgree;
    
    [sender setImage:[UIImage imageNamed:_isAgree?@"recharge_invest_agre":@"recharge_invest_agre01"] forState:UIControlStateNormal];
    
}
/**
 风险提示函
 */
- (IBAction)riskTishi:(UIButton *)sender {
    
    BannerWebViewVC *normalWeb = [[BannerWebViewVC alloc] initWithUrlStr:HYC_Reminder title:self.riskReminderName];
    [self.navigationController pushViewController:normalWeb animated:YES withHideBottomBarWhenPush:YES pop:YES];
}
- (IBAction)invitepro:(id)sender {
    
    BannerWebViewVC *normalWeb = [[BannerWebViewVC alloc] initWithUrlStr:HYC_InvestmentProtocol title:self.investmentAgreementName];
    [self.navigationController pushViewController:normalWeb animated:YES withHideBottomBarWhenPush:YES pop:YES];
}

/**
 懒加载
 */
- (NSArray *)titleArr
{
    if (!_titleArr) {
        _titleArr = @[@"加息券"];
    }
    return _titleArr;
}
- (NSMutableArray *)redList
{
    if (!_redList) {
        _redList = [NSMutableArray array];
    }
    return _redList;
}
- (NSMutableArray *)couponList
{
    if (!_couponList) {
        _couponList = [NSMutableArray array];
    }
    return _couponList;
}
- (void)setNormalModel:(ProjectModel *)normalModel
{
    if (normalModel) {
        self.currentType = normalModel.type;
//        self.navigationItem.title = @"立即投资";
        _productID = normalModel.ID.length<1 ? normalModel.productsId : normalModel.ID;
        
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (range.location>10) {
        return NO;
    }
    
    return YES;
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if (textField == _moneyTF) {
        [self hideKeyBoard];
    }
}

@end



